package com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.dao;

import com.skytech.tax.customsdatawarehouse.singlewindow.processtrade.manual.domain.entity.ManualInvt;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Lianhong
 * @since 2021/11/11
 */
@Repository
public class ManualInvtDao {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private final String saveInvtSql = "INSERT INTO sw_manual_invt " +
            "(seqNo, invt, socialCreditCode, invtDclTime, inputTime, impexpMarkcd, storageTime) VALUES (:seqNo, :invt, :socialCreditCode, :invtDclTime, :inputTime, :impexpMarkcd, :storageTime)";

    public void save(ManualInvt invt) {
        invt.setStorageTime(DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        this.namedParameterJdbcTemplate.update(this.saveInvtSql, new BeanPropertySqlParameterSource(invt));
    }

    private String selectInvtSql = "SELECT seqNo, invt, storageTime FROM sw_manual_invt WHERE 1=1";

    public ManualInvt findBySeqNo(String seqNo) {
        StringBuilder sql = new StringBuilder(this.selectInvtSql);
        List<Object> params = new ArrayList<>();
        if (StringUtils.isNotEmpty(seqNo)) {
            sql.append(" AND seqNo = ? ");
            params.add(seqNo);
        }
        try {
            return namedParameterJdbcTemplate.getJdbcOperations()
                    .queryForObject(sql.toString(), params.toArray(), new BeanPropertyRowMapper<>(ManualInvt.class));
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private String deleteInvtSql = "DELETE FROM sw_manual_invt WHERE seqNo = ?";

    public void delete(String seqNo) {
        this.namedParameterJdbcTemplate.getJdbcOperations().update(this.deleteInvtSql, seqNo);
    }
}
